﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.Scripting.Runtime;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace CoreLims.Models.CoreLims
{
    using User = CommonUser;

    public static class CommonUserExtension
    {
        /// <summary>
        /// 根据ID，获取用户
        /// </summary>
        /// <returns></returns>
        public static User getUserById(this CommonUser User, CoreLimsContext dbContext, string Id) => dbContext.User.FirstOrDefault(m => m.Id == Id);

        /// <summary>
        /// 根据 IDentity 中的登录名获取用户信息
        /// </summary>
        /// <param name="User"></param>
        /// <param name="dbContext"></param>
        /// <param name="identityName"></param>
        /// <returns></returns>
        public static User getUserByIdentityName(this CommonUser User, CoreLimsContext dbContext, string identityName) => dbContext.User.FirstOrDefault(m => m.IdentityName == identityName);

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="User">用户至少要有一个ID值</param>
        /// <param name="dbContext"></param>
        /// <returns></returns>
        public static string AddUser(this CommonUser User, CoreLimsContext dbContext)
        {
            dbContext.Add(User);
            dbContext.SaveChanges();
            return "用户添加成功！";
        }

        /// <summary>
        /// 更新用户基本信息
        /// </summary>
        /// <param name="User"></param>
        /// <param name="dbContext"></param>
        /// <returns></returns>
        public static string UpdateUser(this CommonUser User, CoreLimsContext dbContext)
        {
            CommonUser user = Common.User.getUserById(dbContext, User.Id);
            user = User;
            dbContext.Update(user);
            dbContext.SaveChanges();
            return "用户更新成功！";
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="User"></param>
        /// <param name="dbContext"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public static string DeleteUser(this CommonUser User, CoreLimsContext dbContext, string Id)
        {
            CommonUser user = Common.User.getUserById(dbContext, User.Id);
            if (user != null)
            {
                dbContext.Remove(user);
                dbContext.SaveChanges();
                return "用户删除成功！";
            }
            else
                return "需要删除的用户不存在！";
        }

    }
}
